<template>
  <div class="user-list">
    <h2>用户列表</h2>

    <!-- 按钮触发请求 -->
    <button @click="fetchUsers" :disabled="loading" class="btn">
      {{ loading ? '加载中...' : '获取用户列表' }}
    </button>

    <!-- 加载中提示 -->
    <div v-if="loading" class="loading">正在加载数据...</div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error">{{ error }}</div>

    <!-- 用户列表展示 -->
    <ul v-else class="user-grid">
      <li v-for="user in users" :key="user.id" class="user-card">
        <strong>{{ user.name }}</strong><br>
        {{ user.email }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: [],       // 存储用户数据
      loading: false,  // 控制加载状态
      error: null,     // 错误信息
    };
  },
  methods: {
    async fetchUsers() {
      this.loading = true;
      this.error = null;

      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
        this.users = response.data;
      } catch (err) {
        this.error = '获取用户数据失败，请重试。';
        console.error(err);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.user-list {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.btn {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn:disabled {
  background-color: #aaa;
}

.loading {
  margin-top: 20px;
  color: #555;
}

.error {
  margin-top: 20px;
  color: red;
}

.user-grid {
  list-style: none;
  padding: 0;
  margin-top: 20px;
}

.user-card {
  padding: 10px;
  border-bottom: 1px solid #eee;
}
</style>